package cn.wolfcode.service.impl;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.CodeMsg;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.PayVo;
import cn.wolfcode.domain.UsableIntegral;
import cn.wolfcode.feign.UsableIntegralFeignApi;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.IOrderPayService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class OrderPayServiceImpl implements IOrderPayService {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private UsableIntegralFeignApi usableIntegralFeignApi;

    @Override
    public PayVo buildPauRequest(OrderInfo orderInfo, String notifyUrl, String returnUrl) {
        PayVo vo = new PayVo();
        vo.setBody("秒杀活动" + orderInfo.getSeckillTime() + " 场次成功秒杀1个商品");
        vo.setSubject(orderInfo.getProductName());
        vo.setNotifyUrl(notifyUrl);
        vo.setReturnUrl(returnUrl);
        vo.setTotalAmount(orderInfo.getSeckillPrice().toString());
        vo.setOutTradeNo(orderInfo.getOrderNo());
        return vo;
    }

    @Override
    public void alipay(String orderNo, Integer type) {
        // 基于 orderId 查询订单详情
        OrderInfo orderInfo = orderInfoService.getById(orderNo);

        if (orderInfo == null) {
            throw new BusinessException(SeckillCodeMsg.ORDER_NOT_EXISTS_ERROR);
        }

        // 基于订单详情中的用户 id 查询用户信息
        UsableIntegral usableIntegral = usableIntegralFeignApi.getByUserId(orderInfo.getUserId()).getData();
        if (usableIntegral == null) {
            throw new BusinessException(new CodeMsg(500, "远程调用用户查询积分失败"));
        }
        // 判断是积分支付还是支付宝支付
        if (OrderInfo.PAYTYPE_INTERGRAL == type) {
            // 支付宝支付
            // 判断用户的积分是否满足支付的条件
            if (usableIntegral.getAmount() > orderInfo.getIntergral()) {
                log.info("[用户购买业务] 用户使用积分支付购买{}, 用户总积分: {}, 需支付积分: {}",
                        orderInfo.getProductName(), usableIntegral.getAmount(), orderInfo.getIntergral());
                // 用户积分减少
                usableIntegralFeignApi.pay(orderInfo.getUserId(), orderInfo.getIntergral());

                // 修改用户订单为积分支付
                orderInfoService.payOrder(orderNo, OrderInfo.PAYTYPE_INTERGRAL);
            } else {
                // 用户积分不够
                throw new BusinessException(new CodeMsg(500, "您的积分不足!"));
            }
        }
    }
}
